<template>
  <div class="products-page">
    <front-header></front-header>
    <div class="main-content">
      <!-- 页面标题 -->
      <div class="page-header">
        <h2 class="page-title">
          <i class="el-icon-shopping-bag-1"></i>
          <span>全部商品</span>
        </h2>
        <div class="page-subtitle">精质百货，悦享人生</div>
      </div>

      <div class="products-layout">
        <!-- 左侧筛选区域 -->
        <div class="filter-sidebar">
          <div class="filter-card">
            <div class="filter-section">
              <h3 class="filter-title">
                <i class="el-icon-menu"></i>
                商品分类
              </h3>
              <div class="filter-content">
                <div 
                  class="category-item"
                  :class="{ active: selectedCategory === '' }"
                  @click="handleCategoryChange('')"
                >
                  <span class="category-name">全部商品</span>
                </div>
                <div 
                  v-for="category in categories" 
                  :key="category.id"
                  class="category-item"
                  :class="{ active: selectedCategory === category.id }"
                  @click="handleCategoryChange(category.id)"
                >
                  <span class="category-name">{{ category.name }}</span>
                </div>
              </div>
            </div>

            <div class="filter-section">
              <h3 class="filter-title">
                <i class="el-icon-price-tag"></i>
                价格区间
              </h3>
              <div class="filter-content">
                <div 
                  class="price-item"
                  :class="{ active: priceRange === '' }"
                  @click="handlePriceRangeChange('')"
                >
                  <span>全部价格</span>
                </div>
                <div 
                  v-for="(range, index) in priceRanges" 
                  :key="index"
                  class="price-item"
                  :class="{ active: priceRange === range.value }"
                  @click="handlePriceRangeChange(range.value)"
                >
                  <span>{{ range.label }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧商品展示区域 -->
        <div class="products-container">
          <!-- 搜索和排序 -->
          <div class="products-header">
            <div class="search-box">
              <el-input 
                v-model="searchKeyword" 
                placeholder="搜索商品" 
                prefix-icon="el-icon-search"
                clearable
                @clear="handleSearch"
                @keyup.enter.native="handleSearch"
              >
              </el-input>
            </div>

            <div class="sort-options">
              <span class="sort-label">排序:</span>
              <div class="sort-buttons">
                <div 
                  v-for="option in sortOptions" 
                  :key="option.value"
                  class="sort-button"
                  :class="{ active: sortBy === option.value }"
                  @click="handleSortChange(option.value)"
                >
                  {{ option.label }}
                </div>
              </div>
            </div>
          </div>

          <!-- 已选择的过滤条件 -->
          <div class="selected-filters" v-if="hasFilters">
            <el-tag 
              v-if="selectedCategory" 
              closable
              @close="handleCategoryChange('')"
            >
              分类: {{ getCategoryName(selectedCategory) }}
            </el-tag>
            <el-tag 
              v-if="priceRange" 
              closable
              @close="handlePriceRangeChange('')"
            >
              价格: {{ getPriceRangeLabel(priceRange) }}
            </el-tag>
            <el-tag 
              v-if="sortBy !== 'default'" 
              closable
              @close="handleSortChange('default')"
            >
              {{ getSortLabel(sortBy) }}
            </el-tag>
            <el-tag 
              v-if="searchKeyword" 
              closable
              @close="clearSearch"
            >
              关键词: {{ searchKeyword }}
            </el-tag>
            <el-button size="small" type="text" @click="resetFilters" v-if="hasFilters">
              <i class="el-icon-refresh-right"></i> 重置筛选
            </el-button>
          </div>

          <!-- 商品列表 -->
          <div class="products-grid" v-loading="loading">
            <transition-group name="fade-list" tag="div" class="grid-container">
              <div 
                v-for="product in products" 
                :key="product.id"
                class="product-item"
              >
                <product-card :product="product" />
              </div>
            </transition-group>
            
            <div v-if="!loading && products.length === 0" class="empty-state">
              <i class="el-icon-goods"></i>
              <p>暂无相关商品</p>
              <el-button type="text" @click="resetFilters">清除筛选条件</el-button>
            </div>
          </div>

          <!-- 分页 -->
          <div class="pagination-wrapper" v-if="total > 0">
            <el-pagination
              background
              :current-page.sync="currentPage"
              :page-size="pageSize"
              :total="total"
              :page-sizes="[12, 24, 36, 48]"
              layout="sizes, prev, pager, next, jumper, total"
              @size-change="handleSizeChange"
              @current-change="handlePageChange"
            >
            </el-pagination>
          </div>
        </div>
      </div>
    </div>
    <front-footer></front-footer>
  </div>
</template>

<script>
import FrontHeader from '@/components/front/FrontHeader.vue'
import FrontFooter from '@/components/front/FrontFooter.vue'
import ProductCard from '@/components/front/ProductCard.vue'
import Request from '@/utils/request'
import { debounce } from 'lodash'

export default {
  name: 'Products',
  components: {
    FrontHeader,
    FrontFooter,
    ProductCard
  },
  data() {
    return {
      loading: false,
      products: [],
      categories: [],
      selectedCategory: '',
      priceRange: '',
      priceRanges: [
        { label: '0-50元', value: '0-50' },
        { label: '50-100元', value: '50-100' },
        { label: '100-200元', value: '100-200' },
        { label: '200元以上', value: '200-' }
      ],
      sortOptions: [
        { label: '默认排序', value: 'default' },
        { label: '销量优先', value: 'sales,desc' },
        { label: '价格从低到高', value: 'price,asc' },
        { label: '价格从高到低', value: 'price,desc' }
      ],
      sortBy: 'default',
      searchKeyword: '',
      currentPage: 1,
      pageSize: 12,
      total: 0,
      debouncedSearch: null
    }
  },
  computed: {
    hasFilters() {
      return this.selectedCategory || this.priceRange || this.sortBy !== 'default' || this.searchKeyword
    }
  },
  methods: {
    // 获取商品分类
    async getCategories() {
      try {
        const res = await Request.get('/category/all')
        if (res.code === '0') {
          this.categories = res.data
        }
      } catch (error) {
        console.error('获取分类失败:', error)
      }
    },
    // 获取商品列表
    async getProducts() {
      this.loading = true
      try {
        const params = {
          status: 1,
          currentPage: this.currentPage,
          size: this.pageSize
        }

        // 添加分类筛选
        if (this.selectedCategory) {
          params.categoryId = this.selectedCategory
        }

        // 添加价格区间筛选
        if (this.priceRange) {
          const [min, max] = this.priceRange.split('-')
          if (min) params.minPrice = min
          if (max) params.maxPrice = max
        }

        // 添加排序
        if (this.sortBy !== 'default') {
          const [field, order] = this.sortBy.split(',')
          params.sortField = field
          params.sortOrder = order
        }

        // 添加搜索关键词
        if (this.searchKeyword) {
          params.name = this.searchKeyword
        }

        const res = await Request.get('/product/page', { params })
        if (res.code === '0') {
          if (res.data && res.data.records) {
            this.products = res.data.records.map(product => ({
              ...product,
              isFavorite: false,
              imageUrl: product.imageUrl?.startsWith('http') ? product.imageUrl : `${product.imageUrl}`
            }))
            this.total = res.data.total
          } else {
            this.products = []
            this.total = 0
          }
        } else {
          this.products = []
          this.total = 0
        }
      } catch (error) {
        console.error('获取商品列表失败:', error)
        this.$message.error('获取商品列表失败')
        this.products = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },
    handleCategoryChange(categoryId) {
      this.selectedCategory = categoryId
      this.currentPage = 1
      this.getProducts()
    },
    handlePriceRangeChange(range) {
      this.priceRange = range
      this.currentPage = 1
      this.getProducts()
    },
    handleSortChange(value) {
      this.sortBy = value
      this.currentPage = 1
      this.getProducts()
    },
    handleSearch() {
      this.debouncedSearch()
    },
    handlePageChange(page) {
      this.currentPage = page
      this.getProducts()
    },
    handleRouteChange() {
      const query = {}
      if (this.selectedCategory) {
        query.category = this.selectedCategory
      }
      if (this.searchKeyword) {
        query.keyword = this.searchKeyword
      }
      // 更新URL，但不触发路由变化
      this.$router.replace({ query }).catch(() => {})
    },
    getCategoryName(id) {
      const category = this.categories.find(c => c.id === id)
      return category ? category.name : '全部'
    },
    getPriceRangeLabel(value) {
      const range = this.priceRanges.find(r => r.value === value)
      return range ? range.label : '全部'
    },
    getSortLabel(value) {
      const option = this.sortOptions.find(o => o.value === value)
      return option ? option.label : '默认排序'
    },
    clearSearch() {
      this.searchKeyword = ''
      this.handleSearch()
    },
    resetFilters() {
      this.selectedCategory = ''
      this.priceRange = ''
      this.sortBy = 'default'
      this.searchKeyword = ''
      this.currentPage = 1
      this.getProducts()
    },
    handleSizeChange(size) {
      this.pageSize = size
      this.currentPage = 1
      this.getProducts()
    }
  },
  watch: {
    searchKeyword() {
      this.handleSearch()
      this.handleRouteChange()
    },
    selectedCategory() {
      this.handleRouteChange()
    },
    sortBy() {
      this.currentPage = 1
      this.getProducts()
    }
  },
  created() {
    this.debouncedSearch = debounce(() => {
      this.currentPage = 1
      this.getProducts()
    }, 300)

    this.getCategories()
    this.getProducts()
    
    const { category, keyword } = this.$route.query
    if (category) this.selectedCategory = category
    if (keyword) {
      this.searchKeyword = keyword
      this.handleSearch()
    }
  },
  beforeDestroy() {
    if (this.debouncedSearch) {
      this.debouncedSearch.cancel()
    }
  }
}
</script>

<style scoped>
.products-page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background: linear-gradient(135deg, #fff8e1 0%, #fff3e0 100%);
  position: relative;
  overflow: hidden;
}

/* 背景装饰 */
.products-page::before, .products-page::after {
  content: '';
  position: absolute;
  border-radius: 50%;
  z-index: 0;
}

.products-page::before {
  width: 600px;
  height: 600px;
  top: -200px;
  right: -100px;
  background: linear-gradient(135deg, rgba(255, 152, 0, 0.1), rgba(255, 193, 7, 0.05));
}

.products-page::after {
  width: 400px;
  height: 400px;
  bottom: -100px;
  left: -100px;
  background: linear-gradient(135deg, rgba(255, 152, 0, 0.1), rgba(255, 193, 7, 0.05));
}

.main-content {
  flex: 1;
  max-width: 1400px;
  margin: 0 auto;
  padding: 24px;
  width: 100%;
  box-sizing: border-box;
  position: relative;
  z-index: 1;
}

/* 页面标题样式 */
.page-header {
  margin-bottom: 24px;
  background: transparent;
  padding: 20px 0;
  position: relative;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  border: none;
}

.page-header::before {
  display: none;
}

.page-title {
  display: flex;
  align-items: center;
  gap: 12px;
  margin: 0;
  font-size: 28px;
  font-weight: 600;
  color: #F57C00;
  letter-spacing: 1px;
}

.page-title i {
  font-size: 32px;
  color: #FF9800;
  background: linear-gradient(135deg, #FF9800, #FFC107);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.page-subtitle {
  margin-top: 8px;
  font-size: 16px;
  color: #666;
  padding-left: 0;
}

/* 左右布局 */
.products-layout {
  display: flex;
  gap: 24px;
}

/* 左侧筛选区域 */
.filter-sidebar {
  width: 280px;
  flex-shrink: 0;
}

.filter-card {
  background: white;
  border-radius: 16px;
  padding: 20px;
  border: 1px solid rgba(255, 193, 7, 0.1);
}

.filter-section {
  margin-bottom: 24px;
}

.filter-section:last-child {
  margin-bottom: 0;
}

.filter-title {
  font-size: 16px;
  font-weight: 600;
  color: #F57C00;
  margin: 0 0 16px 0;
  padding-bottom: 12px;
  border-bottom: 1px solid rgba(255, 193, 7, 0.1);
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-title i {
  color: #FF9800;
  font-size: 18px;
}

.filter-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.category-item, .price-item {
  padding: 10px 16px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
  color: #333;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border: 1px solid transparent;
}

.category-item:hover, .price-item:hover {
  background: rgba(255, 193, 7, 0.05);
  transform: translateX(5px);
}

.category-item.active, .price-item.active {
  background: rgba(255, 152, 0, 0.1);
  color: #FF9800;
  font-weight: 500;
  border-left: 3px solid #FF9800;
}

/* 右侧商品展示区域 */
.products-container {
  flex: 1;
  min-width: 0;
}

.products-header {
  background: white;
  border-radius: 16px;
  padding: 16px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  border: 1px solid rgba(255, 193, 7, 0.1);
}

.search-box {
  width: 280px;
}

.search-box :deep(.el-input__inner) {
  border-radius: 8px;
  border: 1px solid rgba(255, 193, 7, 0.2);
  transition: all 0.3s ease;
}

.search-box :deep(.el-input__inner:hover) {
  border-color: rgba(255, 193, 7, 0.4);
}

.search-box :deep(.el-input__inner:focus) {
  border-color: #FF9800;
}

.sort-options {
  display: flex;
  align-items: center;
  gap: 12px;
}

.sort-label {
  font-size: 14px;
  color: #666;
}

.sort-buttons {
  display: flex;
  gap: 8px;
}

.sort-button {
  padding: 6px 12px;
  border-radius: 16px;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.3s ease;
  color: #666;
  background: #f5f7fa;
  border: 1px solid transparent;
}

.sort-button:hover {
  color: #FF9800;
  background: rgba(255, 193, 7, 0.1);
}

.sort-button.active {
  color: white;
  background: linear-gradient(135deg, #FF9800, #FFC107);
  border-color: #FF9800;
}

/* 已选择的过滤条件 */
.selected-filters {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 20px;
  padding: 16px 20px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 16px;
  border: 1px solid rgba(255, 193, 7, 0.1);
  align-items: center;
}

.selected-filters :deep(.el-tag) {
  padding: 0 12px;
  height: 28px;
  line-height: 28px;
  border-radius: 14px;
  background: white;
  border: 1px solid rgba(255, 193, 7, 0.2);
  color: #FF9800;
}

.selected-filters :deep(.el-tag .el-tag__close) {
  background-color: transparent;
  color: #FF9800;
  font-weight: bold;
}

.selected-filters :deep(.el-tag .el-tag__close:hover) {
  background-color: #FF9800;
  color: white;
}

.selected-filters :deep(.el-button--text) {
  color: #FF9800;
  margin-left: auto;
}

.selected-filters :deep(.el-button--text:hover) {
  color: #F57C00;
}

/* 商品网格 */
.products-grid {
  min-height: 400px;
}

.grid-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 24px;
  padding: 4px;
}

.product-item {
  transition: all 0.3s ease;
}

.product-item:hover {
  transform: translateY(-4px);
}

/* 动画效果 */
.fade-list-enter-active, .fade-list-leave-active {
  transition: all 0.3s ease;
}

.fade-list-enter, .fade-list-leave-to {
  opacity: 0;
  transform: translateY(30px);
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 60px 0;
  color: #666;
  background: white;
  border-radius: 16px;
  border: 1px solid rgba(255, 193, 7, 0.1);
}

.empty-state i {
  font-size: 48px;
  margin-bottom: 16px;
  color: #FF9800;
  opacity: 0.6;
}

.empty-state p {
  font-size: 16px;
  margin: 0 0 16px;
}

.empty-state :deep(.el-button--text) {
  color: #FF9800;
}

/* 分页 */
.pagination-wrapper {
  margin-top: 40px;
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

:deep(.el-pagination.is-background .el-pager li:not(.disabled).active) {
  background-color: #FF9800;
}

:deep(.el-pagination.is-background .el-pager li:not(.disabled):hover) {
  color: #FF9800;
}

/* 响应式布局优化 */
@media (max-width: 992px) {
  .products-layout {
    flex-direction: column;
  }

  .filter-sidebar {
    width: 100%;
  }

  .filter-content {
    flex-direction: row;
    flex-wrap: wrap;
    gap: 8px;
  }

  .category-item, .price-item {
    flex: 0 0 auto;
  }

  .products-header {
    flex-direction: column;
    gap: 16px;
  }

  .search-box {
    width: 100%;
  }

  .sort-options {
    width: 100%;
    justify-content: space-between;
  }
}

@media (max-width: 768px) {
  .main-content {
    padding: 16px;
  }

  .page-header {
    margin-bottom: 20px;
    padding: 16px 20px;
  }

  .page-title {
    font-size: 20px;
  }

  .page-title i {
    font-size: 24px;
  }

  .page-subtitle {
    padding-left: 36px;
    font-size: 13px;
  }

  .filter-card {
    padding: 16px;
  }

  .products-header {
    padding: 12px 16px;
  }

  .grid-container {
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
    gap: 16px;
  }

  .sort-buttons {
    flex-wrap: wrap;
  }

  .sort-button {
    font-size: 12px;
    padding: 4px 10px;
  }
}
</style> 